package com.lxk.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxk.pojo.Users;
import com.lxk.service.LoginService;
import com.lxk.service.UsersService;
import com.lxk.util.weixin.WeChatUtil;
import com.lxk.vo.WxUserMiniVO;
import com.lxk.vo.result.CodeMsg;
import com.lxk.vo.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author JohnSoybean
 * @create 2020/7/15 11:35
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/mini")
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private UsersService usersService;

    /**
     * 测试账号登录
     * @return
     */
    @GetMapping("/mock")
    public String mockLogin() {
        return loginService.mockSetAuth();
    }

    /**
     * 1. 根据code获取 session_key和openid
     * 2. 根据这两项登录或存入用户信息
     * jsCode
     * nickName
     * avatarUrl
     * gender
     * province
     * city
     * country
     * @return
     */
    @RequestMapping(value="/oauth2session", method= RequestMethod.POST, produces="application/json;charset=utf-8")
    public Result<String> oauth2Openid(WxUserMiniVO wxUserMiniVO) {
        //判断code是否存在
        String jsCode = wxUserMiniVO.getJsCode();
        if (jsCode == "" || jsCode == null) {
            return Result.error(CodeMsg.WECAHT_CODE_ERR);
        }
        //根据code获取网页授权用户的session_key, openid
        JSONObject jsonObject = WeChatUtil.getSessionKey(jsCode);
        log.info(jsonObject.toJSONString());
        String session_key = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        if (session_key == null) {
            return Result.error(CodeMsg.GET_SESSION_KEY_ERR);
        }
        //业务逻辑 按openid查询
        // TODO 若修改为unionid验证  1.判断openid改为unionid
        Users users = usersService.getOne(new LambdaQueryWrapper<Users>().eq(Users::getOpenid, openid), false);
        if (users == null) {    //若用户不存在，新增用户
            users = usersService.wxUserMiniToUsers(wxUserMiniVO, openid, session_key);
            boolean save = usersService.save(users);
            if (!save) {
                return Result.error(CodeMsg.ADD_USER_ERR);
            }
            //返回token
            Long userId = users.getUserId();
            String token = loginService.setAuth(userId);
            return Result.success(token);
        } else {    //用户存在，更新sessionKey
            // TODO 若修改为unionid验证  2.若存在则更新openid
            //判断是否已被冻结
            if (users.getBlock() == 1) {
                return Result.error(CodeMsg.ACCOUNT_BLOCKED);
            }
            //存入sessionKey
            Users updUser = new Users();
            updUser.setUserId(users.getUserId());
            updUser.setSessionKey(session_key);
            usersService.updateById(updUser);
            //返回token
            Long userId = users.getUserId();
            String token = loginService.setAuth(userId);
            return Result.success(token);
        }
    }

}
